package com.zzr.zzrbackend.service.Impl;

import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.zzr.zzrbackend.config.JwtInterceptor;
import com.zzr.zzrbackend.mapper.*;
import com.zzr.zzrbackend.pojo.domain.*;
import com.zzr.zzrbackend.pojo.dto.CommonResult;
import com.zzr.zzrbackend.pojo.dto.result.*;
import com.zzr.zzrbackend.service.AESService;
import com.zzr.zzrbackend.util.AesEncryptUtils;
import com.zzr.zzrbackend.util.TimeUtil;
import com.zzr.zzrbackend.util.TokenUtils;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

@Service
public class AESServiceImpl implements AESService {

    @Resource
    private DisabuseRecordMapper disabuseRecordMapper;
    @Resource
    private JwtInterceptor jwtInterceptor;
    @Resource
    private UserMapper userMapper;
    @Resource
    private LiveGroupChatRoomMapper liveGroupChatRoomMapper;
    @Resource
    TrackRecordTimeMapper trackRecordTimeMapper;
    @Resource
    HomeInterfaceMapper homeInterfaceMapper;
    @Resource
    UserInfoMapper userInfoMapper;
    @Resource
    EmergePersonMapper emergePersonMapper;

    @Override
    public CommonResult<AESResult> getDisabuseDetail(HttpServletRequest request, Integer disabuseId) throws Exception {
        Integer userId = jwtInterceptor.getUserId(request);
        if (userId == null) return CommonResult.fail_login();
        //获取Disabuse
        DisabuseRecord disabuseRecord = disabuseRecordMapper.selectDisabuseRecordByDisabuseId(disabuseId);
        //初始化返回
        DisabuseResult disabuseResult = setDisabuseResult(disabuseRecord);
        Integer roomId = liveGroupChatRoomMapper.selectIdByDisabuseId(disabuseId);
        disabuseResult.setGroupLiveChatRoomId(roomId);
        try {
            disabuseResult.setGroupLiveChatRoomName(liveGroupChatRoomMapper.selectNameByDisabuseId(disabuseId));
        } catch (Exception e) {
            disabuseResult.setGroupLiveChatRoomName("异常群聊");
            System.out.println(e.getMessage());
        }
        //兼容老版本群聊
        if (disabuseResult.getGroupLiveChatRoomName() == null) {
            disabuseResult.setGroupLiveChatRoomName("id为" + disabuseId + "的老版本群聊");
        }
        //进行加密处理
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(disabuseResult));
        String result;
        try {
            result = AesEncryptUtils.encrypt(jsonObject.toJSONString(), AesEncryptUtils.KEY);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.fail(e.getMessage());
        }
        AESResult aesResult = new AESResult();
        aesResult.setResult(result);
        return CommonResult.success(aesResult);
    }

    @Override
    public CommonResult<AESResult> list(HttpServletRequest request, Integer time) {
        Claims claims = TokenUtils.getClaimsFromJwt(request.getHeader("token"));
        Integer permission = (Integer) claims.get("permission");
        if (!(permission == 1 || permission == 2 || permission == 3)) return CommonResult.fail();
        //将时间戳转化为年月日
        long lt = time;
        String day = TimeUtil.transform(lt);

        List<DisabuseRecord> disabuseRecordList = disabuseRecordMapper.selectAllDisabuseList();
        List<TrackRecordTime> trackRecordTimeList = trackRecordTimeMapper.selectAll();

        List<PostResult> postResultList = new ArrayList<>();
        List<SelectContent> selectContentList = new ArrayList<>();


        HashSet<PostResult> hs = new HashSet<>();

        //遍历disabuseRecord表
        for (DisabuseRecord temp : disabuseRecordList) {
            String nowDay = TimeUtil.transform(temp.getTime());
            if (day.equals(nowDay)) {
                User user1 = userMapper.selectById(temp.getChildId());
                PostResult postResult = new PostResult();
                postResult.setType(temp.getType());
                postResult.setSolveType(temp.getSolveType());
                postResult.setIsNowSolve(temp.getIsNowSolve());
                postResult.setIsFinish(temp.getIsFinish());
                postResult.setTime(temp.getTime());
                postResult.setDisabuseId(temp.getId());
                postResult.setName(user1.getUsername());
                hs.add(postResult);
            }
        }
        for (PostResult temp : hs) {
            postResultList.add(temp);
        }

        HashSet<SelectContent> hs2 = new HashSet<>();
        //遍历trackRecordTime表
        for (TrackRecordTime temp : trackRecordTimeList) {
            String nowDay = TimeUtil.transform(temp.getTime());
            if (day.equals(nowDay)) {

                HomeInterface homeInterface = homeInterfaceMapper.selectById(temp.getContentId());
                User user1 = userMapper.selectById(temp.getUserId());
                SelectContent selectContent = new SelectContent();
                selectContent.setBookName(homeInterface.getName());
                selectContent.setType(homeInterface.getType());
                selectContent.setTime(temp.getTime());
                selectContent.setName(user1.getUsername());

                hs2.add(selectContent);
            }
        }
        for (SelectContent temp : hs2) {
            selectContentList.add(temp);
        }
        //封装返回结果
        TrackRecordListResult trackRecordListResult = new TrackRecordListResult();
        trackRecordListResult.setPostResultList(postResultList);
        trackRecordListResult.setSelectContentList(selectContentList);


        //进行加密处理
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(trackRecordListResult));
        String result;
        try {
            result = AesEncryptUtils.encrypt(jsonObject.toJSONString(), AesEncryptUtils.KEY);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.fail(e.getMessage());
        }
        AESResult aesResult = new AESResult();
        aesResult.setResult(result);

        return CommonResult.success(aesResult);
    }

    @Override
    public CommonResult<AESResult> getMyProfile(HttpServletRequest request) {
        Claims claims = TokenUtils.getClaimsFromJwt(request.getHeader("token"));
        Integer permission = (Integer) claims.get("permission");
        Integer userId = (Integer) claims.get("id");
        if (permission == 1) {
            User user = userMapper.selectById(userId);
            if (user == null) {
                return CommonResult.fail("用户不存在，数据库异常");
            }
            UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
            if (userInfo == null) {
                return CommonResult.fail("数据库异常");
            }
            ChildProfileResult childProfileResult = new ChildProfileResult();
            childProfileResult.setUserName(userInfo.getUserName());
            childProfileResult.setGender(userInfo.getGender());
            childProfileResult.setNativePlace(userInfo.getNativePlace());
            childProfileResult.setAge(userInfo.getAge());
            childProfileResult.setGrade(userInfo.getGrade());
            childProfileResult.setSign(userInfo.getSign());
            childProfileResult.setHeadPicUrl(userInfo.getHeadPicUrl());

            //进行加密处理
            JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(childProfileResult));
            String result;
            try {
                result = AesEncryptUtils.encrypt(jsonObject.toJSONString(), AesEncryptUtils.KEY);
            } catch (Exception e) {
                e.printStackTrace();
                return CommonResult.fail(e.getMessage());
            }
            AESResult aesResult = new AESResult();
            aesResult.setResult(result);

            return CommonResult.success(aesResult);
        } else if (permission == 2) {
            UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
            if (userInfo == null) {
                return CommonResult.fail("数据库异常");
            }

            User user = userMapper.selectById(userId);
            if (user == null) {
                return CommonResult.fail("用户不存在，数据库异常");
            }
            ParentProfileResult parentProfileResult = new ParentProfileResult();
            parentProfileResult.setUserName(userInfo.getUserName());
            parentProfileResult.setPhone(user.getPhone());
            parentProfileResult.setGender(userInfo.getGender());
            parentProfileResult.setAge(userInfo.getAge());
            parentProfileResult.setRelation(userInfo.getRelation());
            parentProfileResult.setNativePlace(userInfo.getNativePlace());
            parentProfileResult.setWorkAddress(userInfo.getWorkAddress());
            parentProfileResult.setHomeSituation(userInfo.getHomeSituation());
            parentProfileResult.setSoftwareSituation(userInfo.getSoftwareSituation());
            parentProfileResult.setRemarkChild(userInfo.getRemarkChild());
            parentProfileResult.setRemarkVolunteer(userInfo.getRemarkVolunteer());
            parentProfileResult.setHeadPicUrl(userInfo.getHeadPicUrl());

            //进行加密处理
            JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(parentProfileResult));
            String result;
            try {
                result = AesEncryptUtils.encrypt(jsonObject.toJSONString(), AesEncryptUtils.KEY);
            } catch (Exception e) {
                e.printStackTrace();
                return CommonResult.fail(e.getMessage());
            }
            AESResult aesResult = new AESResult();
            aesResult.setResult(result);

            return CommonResult.success(aesResult);
        } else if (permission == 3) {
            UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
            VolunteerProfileResult volunteerProfileResult = new VolunteerProfileResult();
            volunteerProfileResult.setUserName(userInfo.getUserName());
            volunteerProfileResult.setGender(userInfo.getGender());
            volunteerProfileResult.setNativePlace(userInfo.getNativePlace());
            volunteerProfileResult.setAge(userInfo.getAge());
            volunteerProfileResult.setWorkAddress(userInfo.getWorkAddress());
            List<String> list = Convert.toList(String.class, userInfo.getGoodSolveProblem());
            volunteerProfileResult.setGoodSolveProblems(list);
            volunteerProfileResult.setLoginDuration(userInfo.getLoginDuration());
            volunteerProfileResult.setIsOfflineSolution(userInfo.getIsOfflineSolution());
            volunteerProfileResult.setRemarkChild(userInfo.getRemarkChild());
            volunteerProfileResult.setOther(userInfo.getOther());
            volunteerProfileResult.setHeadPicUrl(userInfo.getHeadPicUrl());

            //进行加密处理
            JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(volunteerProfileResult));
            String result;
            try {
                result = AesEncryptUtils.encrypt(jsonObject.toJSONString(), AesEncryptUtils.KEY);
            } catch (Exception e) {
                e.printStackTrace();
                return CommonResult.fail(e.getMessage());
            }
            AESResult aesResult = new AESResult();
            aesResult.setResult(result);

            return CommonResult.success(aesResult);
        }
        return CommonResult.fail("权限异常");
    }

    @Override
    public CommonResult<AESResult> getEmergePerson(HttpServletRequest request) {
        Claims claims = TokenUtils.getClaimsFromJwt(request.getHeader("token"));
        Integer userId = (Integer) claims.get("id");
        User user = userMapper.selectById(userId);
        if (user == null) {
            return CommonResult.fail("用户不存在，数据库异常");
        }
        if (user.getPermission() != 1) {
            return CommonResult.fail("权限验证失败，不是小孩账号");
        }

        List<EmergePerson> emergePersonList = emergePersonMapper.selectAll();
        EmergePersonResult emergePersonResult = new EmergePersonResult();

        emergePersonResult.setEmergePersonList(emergePersonList);

        //进行加密处理
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(emergePersonResult));
        String result;
        try {
            result = AesEncryptUtils.encrypt(jsonObject.toJSONString(), AesEncryptUtils.KEY);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.fail(e.getMessage());
        }
        AESResult aesResult = new AESResult();
        aesResult.setResult(result);

        return CommonResult.success(aesResult);
    }

    /**
     * 装载disabuseResult
     */
    private DisabuseResult setDisabuseResult(DisabuseRecord disabuseRecord) {
        DisabuseResult disabuseResult = new DisabuseResult();
        disabuseResult.setId(disabuseRecord.getId());
        disabuseResult.setName(userMapper.selectUserNameById(disabuseRecord.getChildId()));
        disabuseResult.setChildId(disabuseRecord.getChildId());
        disabuseResult.setQuestion(disabuseRecord.getQuestion());
        //处理type
        if (disabuseRecord.getType() == 1) {
            disabuseResult.setType("心理");
        } else if (disabuseRecord.getType() == 2) {
            disabuseResult.setType("学习");
        } else if (disabuseRecord.getType() == 3) {
            disabuseResult.setType("安全");
        } else if (disabuseRecord.getType() == 4) {
            disabuseResult.setType("生活");
        } else if (disabuseRecord.getType() == 5) {
            disabuseResult.setType("兴趣");
        } else if (disabuseRecord.getType() == 6) {
            disabuseResult.setType("感情");
        } else if (disabuseRecord.getType() == 7) {
            disabuseResult.setType("健康");
        }
        //处理solve_type
        if (disabuseRecord.getSolveType() == 1) {
            disabuseResult.setSolveType("线下");
        } else if (disabuseRecord.getSolveType() == 2) {
            disabuseResult.setSolveType("视频");
        } else if (disabuseRecord.getSolveType() == 3) {
            disabuseResult.setSolveType("语音");
        } else if (disabuseRecord.getSolveType() == 4) {
            disabuseResult.setSolveType("文字");
        }
        //处理是否匿名
        disabuseResult.setIsAnonymous(disabuseRecord.getIsAnonymous());
        //处理是否立即解决
        disabuseResult.setIsNowSolve(disabuseRecord.getIsNowSolve());
        //处理是否完成
        disabuseResult.setIsFinish(disabuseRecord.getIsFinish());
        disabuseResult.setTime(disabuseRecord.getTime());
        disabuseResult.setIsAccept(disabuseRecord.getIsAccept());
        //返回
        return disabuseResult;
    }
}
